package com.maosy.demo.api

import com.maosy.demo.exceptions.InitFailException
import com.maosy.demo.util.gson
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

object HttpRequest {

    private lateinit var mRetrofit: MutableMap<ServerHost, Retrofit>

    fun init() {
        if (this::mRetrofit.isInitialized) {
            mRetrofit.clear()
        } else {
            mRetrofit = mutableMapOf()
        }

        if (ServerHost.values().isEmpty()) {
            throw InitFailException("ServerHost is empty")
        }

        ServerHost.values().forEach {
            val client = OkHttpClient.Builder().build()
            val retrofit = Retrofit.Builder()
                .baseUrl(it.host)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
            mRetrofit[it] = retrofit
        }
    }

    fun <T> getApi(host: ServerHost): T {
        if (!this::mRetrofit.isInitialized) {
            throw InitFailException("HttpRequest not initialized")
        }

        val api = mRetrofit[host]
            ?.create(host.api)
            ?: throw InitFailException("HttpRequest not initialized")
        return api as T
    }

}